﻿//
// File: UpdateArt01.cs
//
// This sample program shows how to get a resized image of folder.jpg.  If the image width or
// height is greater than 'scale', the larger will be reduced to scale with the image kept
// in the same aspect.
//

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace ResizeArt01
{
    class Program
    {
        static int scale = 200;
        static string dirName = @"C:\TESTDIR";

        static void Main ()
        {
            Image tagPic;

            ImageCodecInfo jpegEncoder = GetEncoder (ImageFormat.Jpeg);
            EncoderParameters encParms = new EncoderParameters (1);
            encParms.Param[0] = new EncoderParameter (Encoder.Quality, 95L);

            string folderFileName = dirName + Path.DirectorySeparatorChar + "folder.jpg";

            using (Image folderPic = Image.FromFile (folderFileName))
            {
                if (folderPic.Width <= scale && folderPic.Height <= scale)
                {
                    Console.WriteLine ("Image does not require reduction");
                    tagPic = folderPic;
                }
                else
                {
                    Console.WriteLine ("Reducing image to max dimension of " + scale);

                    // Proportion new dimensions.
                    int xSize, ySize;
                    if (folderPic.Width <= folderPic.Height)
                    {
                        xSize = (int) (scale * ((float) folderPic.Width / (float) folderPic.Height) + 0.5);
                        ySize = scale;
                    }
                    else
                    {
                        xSize = scale;
                        ySize = (int) (scale * ((float) folderPic.Height / (float) folderPic.Width) + 0.5);
                    }

                    // Resize the folder image.  Tests show this blends source pixels.
                    Image resizedPic = new Bitmap (folderPic, new Size (xSize, ySize));
                    var picStream = new MemoryStream ();

                    // Encode bitmap to Jpeg byte stream.
                    resizedPic.Save (picStream, jpegEncoder, encParms);
                    tagPic = Image.FromStream (picStream);
                }

                var saveName = dirName + Path.DirectorySeparatorChar + @"folderMax-" + scale + ".jpg";
                Console.WriteLine ("Saving possibly resized artwork to {0}", saveName);
                tagPic.Save (saveName);
            }
        }


        static ImageCodecInfo GetEncoder (ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

            foreach (ImageCodecInfo codec in codecs)
                if (codec.FormatID == format.Guid)
                    return codec;

            return null;
        }
    }
}
